package com.quasar.hpatient.module.mine_password;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import com.mob.MobSDK;
import com.quasar.hpatient.api.HttpClient;
import com.quasar.hpatient.api.HttpParams;
import com.quasar.hpatient.bean.comm_regist.RegistBean;

import java.util.HashMap;
import java.util.regex.Pattern;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import lib.quasar.base.frame.BasePresenter;
import lib.quasar.base.frame.OnModelAcceptChangeListener;
import lib.quasar.context.BaseApp;
import lib.quasar.context.BaseConstant;
import lib.quasar.db.manager.DBManager;
import lib.quasar.db.table.User;
import lib.quasar.widget.timer.TimerView;
import okhttp3.RequestBody;

/**
 * description: 修改密码
 * created by kalu on 2018/5/17 13:37
 */
public class MinePasswordPresenter implements BasePresenter {

    @SuppressLint("CheckResult")
    void sendCode(MinePasswordView view, TimerView timer, TextView button) {

        if (null == view || null == timer || null == button)
            return;

        final User patient = DBManager.getInstance().syncGetUserModel();
        if (null == patient) {
            view.toast("获取用户信息发生错误, 请重新登录");
            return;
        }

        final String number = patient.getPhone();
        if (TextUtils.isEmpty(number) || number.length() != 18) {
            view.toast("获取用户手机号发生错误, 请重新登录");
            return;
        }

        final Pattern compile1 = Pattern.compile("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$");
        if (!compile1.matcher(number).matches()) {
            view.toast("用户手机号格式错误, 请重新登录");
            return;
        }

        Observable.create((ObservableOnSubscribe<Boolean>) e -> {

            MobSDK.init(BaseApp.getContext(), BaseConstant.MOB_NAME, BaseConstant.MOB_ID);
            SMSSDK.registerEventHandler(new EventHandler() {
                public void afterEvent(int event, int result, Object data) {
                    SMSSDK.unregisterAllEventHandler();
                    e.onNext(result == SMSSDK.RESULT_COMPLETE);
                }
            });
            // 触发操作
            SMSSDK.getVerificationCode(BaseConstant.MOB_PHONE, number);

        }).subscribeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> {

                    view.toast(aBoolean ? "发送验证码成功" : "发送验证码失败");
                    if (aBoolean) {

                        view.setVisibility(button, aBoolean ? View.GONE : View.VISIBLE);
                        view.setVisibility(timer, aBoolean ? View.VISIBLE : View.GONE);

                        timer.setOnCountdownChangeListener(() -> {
                            view.setVisibility(button, aBoolean ? View.VISIBLE : View.GONE);
                            view.setVisibility(timer, aBoolean ? View.GONE : View.VISIBLE);
                        });
                        timer.startTimer();
                    }
                });
    }

    @SuppressLint("CheckResult")
    void forgetPassword(MinePasswordView view, TextView codes, TextView newPassword, TextView surePassword) {

        if (null == view || null == codes || null == newPassword || null == surePassword) return;

        final String news = newPassword.getText().toString().trim();
        final String sure = surePassword.getText().toString().trim();

        if (TextUtils.isEmpty(news)) {
            view.toast("新密码不能为空");
            return;
        }

        if (TextUtils.isEmpty(sure)) {
            view.toast("确认密码不能为空");
            return;
        }

        if (!sure.equals(news)) {
            view.toast("新密码两次输入不一致");
            return;
        }

        final User patient = DBManager.getInstance().syncGetUserModel();
        if (null == patient) {
            view.toast("获取用户信息发生错误, 请重新登录");
            return;
        }

        final String number = patient.getPhone();
        if (TextUtils.isEmpty(number)) {
            view.toast("获取用户手机号发生错误, 请重新登录");
            return;
        }

        final String code = codes.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            view.toast("验证码不能为空");
            return;
        }

        Observable.create((ObservableOnSubscribe<Boolean>) e -> {

            MobSDK.init(BaseApp.getContext(), BaseConstant.MOB_NAME, BaseConstant.MOB_ID);
            SMSSDK.registerEventHandler(new EventHandler() {
                public void afterEvent(int event, int result, Object data) {
                    SMSSDK.unregisterAllEventHandler();
                    e.onNext(result == SMSSDK.RESULT_COMPLETE);
                }
            });
            // 触发操作
            SMSSDK.submitVerificationCode(BaseConstant.MOB_PHONE, number, code);

        }).subscribeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> {
                    view.toast(aBoolean ? "验证码验证成功" : "验证码验证失败");
                    if (!aBoolean) return;

                    final HashMap<String, Object> map = new HashMap<>();
                    map.put(HttpParams.PASSWORD, sure);
                    map.put(HttpParams.PHONE, number);
                    map.put(HttpParams.USER_TYPE, BaseConstant.TWO);

                    final RequestBody params = createParams(map, HttpParams.DATA_TYPE_1_12);
                    final Observable observable = HttpClient.getSingleHolder().getHttpService().modifyPassword(params);

                    request(observable, new OnModelAcceptChangeListener<RegistBean>() {

                        @Override
                        public void modelSucc(RegistBean result) {
                            view.toast("修改密码成功");
                            view.logout();
                        }
                    });

                });
    }

    void modifyPassword(MinePasswordView view, TextView password1, TextView password2, TextView password3) {

        if (null == view || null == password1 || null == password2) return;

        final String olds = password1.getText().toString().trim();
        final String news = password2.getText().toString().trim();
        final String sure = password3.getText().toString().trim();

        if (TextUtils.isEmpty(olds)) {
            view.toast("旧密码不能为空");
            return;
        }

        if (TextUtils.isEmpty(news)) {
            view.toast("新密码不能为空");
            return;
        }

        if (TextUtils.isEmpty(sure)) {
            view.toast("确认密码不能为空");
            return;
        }

        if (!sure.equals(news)) {
            view.toast("新密码两次输入不一致");
            return;
        }

        final User patient = DBManager.getInstance().syncGetUserModel();
        if (null == patient) {
            view.toast("获取用户信息发生错误, 请重新登录");
            return;
        }

        final String number = patient.getPhone();
        if (TextUtils.isEmpty(number)) {
            view.toast("获取用户手机号发生错误, 请重新登录");
            return;
        }

        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.PASSWORD, news);
        map.put(HttpParams.OLD_PASSWORD, olds);
        map.put(HttpParams.PHONE, number);
        map.put(HttpParams.USER_TYPE, HttpParams.USER_PATIENT);
        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_1_11);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().modifyPassword(params);

        request(observable, new OnModelAcceptChangeListener<RegistBean>() {

            @Override
            public void modelSucc(RegistBean result) {
                view.toast("修改密码成功");
            }
        });
    }

    @Override
    public void recycler() {
    }
}
